package com.zjt.smart.app;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;

import com.zjt.smart.ui.activity.SplashActivity;
import com.zjt.smart.util.FileUtil;
import com.zjt.smart.util.LogUtil;
import com.zjt.smart.util.SharePreferenceUtil;
import com.zjt.smart.util.ToastUtil;

import java.io.File;
import java.io.IOException;

/**
 * 崩溃重启
 */

public class UncaughtHandler implements Thread.UncaughtExceptionHandler {
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    MainApplication application;

    public UncaughtHandler(MainApplication application){
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.application = application;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if(!handleException(ex) && mDefaultHandler != null){
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        }else{
            try{
                logThrowable(ex);
                Thread.sleep(2000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            long lastCrash = SharePreferenceUtil.read().getLong(PreferenceConstant.KEY_CRASH_TIME,0);
            //防止无限重启
            if (System.currentTimeMillis() - lastCrash > 20 * 1000) {
                Intent intent = new Intent(application, SplashActivity.class);
                PendingIntent restartIntent = PendingIntent.getActivity(
                        application, 0, intent, 0);
                AlarmManager mgr = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
                mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                        restartIntent); // 1秒钟后重启应用
            }
            SharePreferenceUtil.write().putLong(PreferenceConstant.KEY_CRASH_TIME, System.currentTimeMillis()).commit();
            //退出程序
            application.exit();
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                ToastUtil.showToast("很抱歉,程序出现异常,即将退出.");
                Looper.loop();
            }
        }.start();
        return true;
    }

    private void logThrowable(Throwable ex) {
        String logStr = Log.getStackTraceString(ex);
        LogUtil.fatal(logStr);
        String extPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        String path = extPath+ File.separator+ Config.CRASH_LOG_PATH;
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        String fileName = path + File.separator + System.currentTimeMillis()+".log";
        try {
            FileUtil.writeFile(fileName,logStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
